 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=29 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Immutable objects
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='field,final,set,synchronized,design pattern,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Immutable objects</div>

<div class='main-body'>
 
<br>Immutable objects are simply objects whose state (the object's data) cannot change after construction.
Examples of immutable objects from the JDK include 
<tt><a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html'>String</a></tt> and 
<tt><a href='http://java.sun.com/javase/6/docs/api/java/lang/Integer.html'>Integer</a></tt>.


<p>Immutable objects greatly simplify your program, since they :
<ul>
<li>
are simple to construct, test, and use</li>

<li>
are automatically <a href="TopicAction234f-2.html">thread-safe</a> and have no synchronization
issues</li>

<li>
do not need a <a href="TopicAction6f4f-2.html">copy constructor</a></li>

<li>
do not need an implementation of <tt><a href="TopicActioned8c-2.html">clone</a></tt></li>

<li>
allow <tt><a href="TopicAction78db-2.html">hashCode</a></tt> to use <a href="TopicAction88f9-2.html">lazy initialization</a>, 
and to cache its return value</li>

<li>
do not need to be <a href="TopicAction79f1-2.html">copied defensively</a> when used
as a field</li>

<li>
make good <tt>Map</tt> keys and <tt>Set</tt> elements (these objects must
not change state while in the collection)</li>

<li>
have their <a href="TopicAction0d31-2.html">class invariant</a> established once upon construction,
and it never needs to be checked again</li>

<li>always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state

</ul>

<span class='highlight'>Immutable objects have a very compelling list of positive qualities.
Without question, they are among the simplest and most robust kinds of classes you can possibly build.
When you create immutable classes, entire categories of problems simply disappear.</span>


<P>Make a class immutable by following these guidelines :
<ul>

<li>ensure the class cannot be overridden - make the class <tt>final</tt>, or
use static factories and keep constructors private</li>

<li>make fields <tt>private</tt> and <tt>final</tt></li>

<li>force callers to construct an object completely in a single step, instead of using a no-argument constructor
combined with subsequent calls to <tt>setXXX</tt> methods (that is, <a href="TopicActionfbbc-2.html">avoid the Java Beans convention</a>)</li>

<li>do not provide any methods which can change the state of the object in
any way - not just <tt>setXXX</tt> methods, but any method which can change
state</li>

<li>if the class has any mutable object fields, then they must be 
<a href='TopicAction79f1-2.html?Id=15'>defensively copied</a> when passed between the class and its caller</li>

</ul>

In <i><a href="http://www.amazon.com/exec/obidos/ASIN/0321356683/ref=nosim/javapractices-20">Effective Java</a></i>, Joshua Bloch makes this compelling recommendation :
<p><b>"Classes should be immutable unless there's a very good reason to
make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."</b>

<P>It's interesting to note that 
<tt><a href='http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html'>BigDecimal</a></tt> 
is technically <em>not</em> immutable, since it's not <tt>final</tt>.


<p><b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.Date;

<span class='comment'>/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Planet {

  <span class='keyword'>public</span> Planet (<span class='keyword'>double</span> aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     <span class='comment'>//make a private copy of aDateOfDiscovery
</span>     <span class='comment'>//this is the only way to keep the fDateOfDiscovery
</span>     <span class='comment'>//field private, and shields this class from any changes that 
</span>     <span class='comment'>//the caller may make to the original aDateOfDiscovery object
</span>     fDateOfDiscovery = <span class='keyword'>new</span> Date(aDateOfDiscovery.getTime());
  }

  <span class='comment'>/**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>double</span> getMass() {
    <span class='keyword'>return</span> fMass;
  }

  <span class='comment'>/**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */</span>
  <span class='keyword'>public</span> String getName() {
    <span class='keyword'>return</span> fName;
  }

<span class='comment'>//  /**
</span><span class='comment'>//  * Returns a mutable object - likely bad style.
</span><span class='comment'>//  *
</span><span class='comment'>//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
</span><span class='comment'>//  * since the Date object state can be changed both by this class and its caller.
</span><span class='comment'>//  * That is, this class is no longer in complete control of fDate.
</span><span class='comment'>//  */
</span><span class='comment'>//  public Date getDateOfDiscovery() {
</span><span class='comment'>//    return fDateOfDiscovery;
</span><span class='comment'>//  }
</span>
  <span class='comment'>/**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */</span>
  <span class='keyword'>public</span> Date getDateOfDiscovery() {
    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDateOfDiscovery.getTime());
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='comment'>/**
  * Final primitive data is always immutable.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>double</span> fMass;

  <span class='comment'>/**
  * An immutable object field. (String objects never change state.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;

  <span class='comment'>/**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> Date fDateOfDiscovery;
}
 
</PRE>
<br>
<br>Note that <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html">javadoc
1.4</a> includes the <tt>-tag</tt> option, whereby simple custom tags may
be defined. One might define an <tt>@is.Immutable</tt> tag, for example,
to document a class as being immutable.

<P>You might also consider defining your own <a href='TopicAction7ce2-2.html?Id=240'>tag interface</a> for immutable objects.
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction0d31-2.html?Id=6'>Validate state with class invariants</a> <br>
 
  
  <a href='TopicAction6f4f-2.html?Id=12'>Copy constructors</a> <br>
 
  
  <a href='TopicAction79f1-2.html?Id=15'>Defensive copying</a> <br>
 
  
  <a href='TopicAction8d16-2.html?Id=21'>Factory methods</a> <br>
 
  
  <a href='TopicAction50dc-2.html?Id=23'>Use final liberally</a> <br>
 
  
  <a href='TopicAction78db-2.html?Id=28'>Implementing hashCode</a> <br>
 
  
  <a href='TopicAction88f9-2.html?Id=34'>Lazy initialization</a> <br>
 
  
  <a href='TopicAction234f-2.html?Id=48'>Document thread safety</a> <br>
 
  
  <a href='TopicActionfbbc-2.html?Id=84'>Avoid JavaBeans style of construction</a> <br>
 
  
  <a href='TopicActiond08d-2.html?Id=187'>Model Objects</a> <br>
 
  
  <a href='TopicAction7ce2-2.html?Id=240'>Tag or marker interfaces</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='29'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=29 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
